<?php


namespace App\Http\Controllers\Merchant;
use App\Http\Controllers\BaseController;
use App\Models\AdvInvite;
use App\Models\Balance;
use App\Models\Merchant;
use App\Models\User;
use Illuminate\Http\Request;

class MerchantController extends BaseController
{

    public $model = Merchant::class;

    public function index(Request $request) {
        $platform_account = $request->input('platform_account');

        $list = Merchant::when($platform_account, function ($q)use($platform_account) {
            $q->where('platform_account', 'like', '%'. $platform_account . '%');
        })->where('audit_status', 1)->where('is_black', 1)->where('category', Merchant::DAREN)->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function child(Request $request) {
        $merchant_id = $this->getUserId();
        $input = $request->input();
        $search = ['start_at' => '', 'end_at' => '', 'nickname' => ''];
//        $arr_id = User::apply($search, $input)->where('rec_merchant_id', $merchant_id)->pluck('id')->all();

        $order_by_key = $request->input('order_by_key', 'total');
        $order_by_value = $request->input('order_by_value', 'desc');


        $list = User::apply($search, $input)->where('rec_merchant_id', $merchant_id)->paginate(per_page());
        foreach ($list as &$item) {
            $total = Balance::where('merchant_id', $merchant_id)->whereIn('type', [Balance::TYPE_MALL, Balance::TYPE_VIP])
                ->where('user_id', $item->id)->sum('amount');
            $item->commission_yuan = format_yuan($total);;
            $item->join_at = (string)$item->created_at;
        }
        return $this->paginate($list);

        $list = Balance::where('merchant_id', $merchant_id)
            ->when(!empty($arr_id), function ($q) use($arr_id){
            $q->whereIn('user_id', $arr_id);
        })->groupBy('user_id')->selectRaw('user_id, sum(amount) as total')
            ->orderBy($order_by_key, $order_by_value)
            ->paginate(\request('per_page', 20));

        if ($list) {
            foreach ($list as &$item) {
                $user = User::find ($item->user_id);
                $time = '';
                if ($user) {
                    $time = (string)$user->created_at;
                }

                $item->nickname = $user->nickname ?? '';
                $item->join_at = $time;
                $item->commission_yuan = format_yuan($item->total);
            }
        }
        return $this->paginate($list);
    }

    public function info(Request $request) {
        $id = \request("id");
        $info = $this->model::find($id);
        //判断是否合作
        $user_id = $this->getUserId();
        $info->has_invite = AdvInvite::where('producer_id', $user_id)->where('daren_id', $id)->exists();
        $info->type = $info->type_show;
        return $this->success($info);
    }

}

